<template>
	<view class="contain">
		
		<!-- heightFix -->
		<view class="head w.-[100%]"><image src="https://guangxins.oss-cn-shenzhen.aliyuncs.com/images/bg/buybg.jpg" mode="widthFix" style="width:100%;"></image></view>
		
		<!-- 测试 -->
		<!-- <view style="margin:30rpx auto;">loginCode:{{loginCode}}</view>
		<view style="margin:30rpx auto;">慢病映射登录:{{mbParaTest}}</view>
		<view style="margin:30rpx auto;">para下单参数:{{paraTest}}</view> -->
		
		<view class="m-auto .w-[80%] flex justify-between mb-5">
			<view class="blod" @click="goOrders">←充值记录</view>
			<view class="blod" @click="gomine">个人中心→</view>
		</view>
		
		<view class="taocan">
			<view class="box"><image @click="buymode('Ai慢病管理')" src="https://guangxins.oss-cn-shenzhen.aliyuncs.com/images/bg/aibuy.png" mode="aspectFill"></image></view>
			<!-- <view class="box"><image @click="buymode('广心智康抑郁焦廖访谈EADI')" src="https://guangxins.oss-cn-shenzhen.aliyuncs.com/images/bg/t1.png" mode="aspectFill"></image></view>
			<view class="box"><image @click="buymode('老人痴呆访谈')" src="https://guangxins.oss-cn-shenzhen.aliyuncs.com/images/bg/t2.png" mode="aspectFill"></image></view> -->
			<view class="box" v-if="showXinLi"><image @click="buymode('认知行为成长站套餐')" src="https://guangxins.oss-cn-shenzhen.aliyuncs.com/images/bg/t3.png" mode="aspectFill"></image></view>
		</view> <!-- taocan -->
	</view> <!-- contain -->
	
	<u-action-sheet :actions="monthList" :title="mtitle" :show="showSelectMonth" :closeOnClickOverlay="true" @select="selectm" @close="closem"></u-action-sheet>
	
</template>

<script setup lang='ts'>
import { ref,reactive } from 'vue'
import {  onLoad,onShow } from '@dcloudio/uni-app'
import {generateOrder,payOrder} from '@/utils/utils'
import { userStore } from '@/stores/userStore'
import {Date_C,addMonths} from '@/common/date.js'
let { hasLogin,userData } = userStore();

let loginCode=ref('');
let paraTest=ref('');
let mbParaTest=ref('');

let ai_buyName=ref('Ai慢病管理');
let xinli_price=ref(127100);
let showXinLi=ref(true);

//Ai慢病
let mbuserid=ref('');
let showSelectMonth=ref(false);
let payMode=ref('');
let aiPay=ref(false);
let mtitle=ref('选择购买月数');
let monthList=reactive<any>([
	{name:'1个月'},
	{name:'2个月'},
	{name:'3个月'},
	{name:'6个月'},
	{name:'12个月'}
]);

let isCanBuy=ref(true); //是否已购买过当前课程
let realPayMoney=ref(127100);
let merchant=reactive<any>({
	buyerUserId:'', //购买者id
	name:'心理筛查', //分类统一使用 "心理筛查"
	tel:'13790977841',
	adr:'广东湛江',
	class:'健康',
	desc:'心理疏导',
	photo:'',
	month:'1',
	price:xinli_price.value, //测试金额 0.01 127100
	lat:20.12345,
	lng:110.666588,
});

const selectm=(e:any)=>{
	console.log("选择的月份",e.name);
	merchant.month=e.name;
	merchant.price=1000;
	realPayMoney.value=merchant.price* parseInt(merchant.month.replace("个月","")); //10元 * 购买月份
	merchant.desc=ai_buyName.value;	  //'Ai慢病管理'	
	aiPay.value=true;
	GenerateOrder();
}

const closem=()=>{
	showSelectMonth.value=false;
}


//慢病映射登录
const mbMappingLoign=()=>{
	let paraData={
		logincode:loginCode.value,
		mbuserid:mbuserid.value
	};
	mbParaTest.value=JSON.stringify(paraData);
	uni.$tools.Reqeust('https://guangxins.cn/AI/mbuserlogin',paraData,'POST').then((res:any)=>{
		console.log("慢病映射登录",res);
		if(res.data.code===200){
			uni.setStorageSync("token",res.data.token);
		}
	});
}

const checkLogin=()=>{
	let msg="请登录后操作";
	if(hasLogin===false || userData.userinfo===null){
			msg="请登录后购买，点击【确定】登录";
			uni.showModal({
					title:"温馨提示",
					content:msg,
					showCancel:true,
					success:res=>{
						if(res.confirm){
							uni.$tools.GoUrl("/pages/login/login",1);
						}
					}
			})
			return false;
	}
	return true;
}

const goOrders=()=>{
	uni.$tools.GoUrl("/pages/sjorders/sjorders");
}

const gomine=()=>{
	uni.$tools.GoUrl("/pages/mine/mine",2);
}

const buymode=(mode:string)=>{
	payMode.value=mode;
	if(mode===ai_buyName.value){ //'Ai慢病管理'	
		merchant.buyerUserId=mbuserid.value;
		merchant.name=mode;
		merchant.class=mode;
		showSelectMonth.value=true;	
	}else{
		if(!checkLogin()){
			return;
		}//检查登录
		uni.$tools.Toast(mode);
		merchant.class=mode;
		if(userData.userinfo.studyname===mode && userData.userinfo.studybuy===true){
			uni.$tools.Toast("当前课程已购买");
			return;
		}	
		merchant.price=xinli_price.value; //心理咨询价格 127100
		GenerateOrder();
	}
}

onLoad((opt)=>{
	if(opt?.mbuserid!=null){
		showXinLi.value=false;
		mbuserid.value=opt?.mbuserid;
		if(mbuserid.value!=""){
			uni.setStorageSync("mbuserid",mbuserid.value);
			console.log("/buy/buy/onLoad",mbuserid.value);
		}
		/*
		if(opt?.logincode!=null){
			loginCode.value=opt?.logincode;
			uni.setStorageSync("logincode",loginCode.value);
		}
		//*/
		//mbMappingLoign();
	}
	//*/
	// let paraPayData:any={};
	// uni.$tools.Reqeust("/api/aaa",paraPayData,'POST').then((res:any)=>{
	// 	console.log("/api/aaa:",res);
	// })
	/*
		uni.login({
			  provider: 'weixin',
			  onlyAuthorize:true,
			  success:e=> {
				//登录。注册会员信息
				if(e.errMsg==='login:ok' && e.code!=null){
					loginCode.value=e.code;
					console.log("微信 login code:",loginCode.value);							
				}
			  }
		});
	//*/
});

onShow(()=>{
	/*
	if(uni.getStorageSync("logincode")!=null){
		loginCode.value=uni.getStorageSync("logincode") || null;
		console.log("buy onShow LoginCode111",loginCode.value);
	}
	//*/
	setTimeout(()=>{
		if(uni.getStorageSync("mbuserid")!=null){
			showXinLi.value=false;
			mbuserid.value=uni.getStorageSync("mbuserid") || null;
			console.log("/buy/buy/onshow",mbuserid.value);
		}
		if(uni.getStorageSync("logincode")!=null){
			loginCode.value=uni.getStorageSync("logincode") || null;
			console.log("buy onShow LoginCode222",loginCode.value);
			mbMappingLoign();
		}		
	},2000);
	


	/*
	if(mbuserid.value!=null && mbuserid.value!=""){
		if(loginCode.value==="" || loginCode.value===null){
			uni.login({
				  provider: 'weixin',
				  onlyAuthorize:true,
				  success:e=> {
					//登录。注册会员信息
					if(e.errMsg==='login:ok' && e.code!=null){
						loginCode.value=e.code;
						console.log("onshow 微信loginCode:",loginCode.value);							
					}
				  }
			});		
		}
	}		
	//*/
	
	GetPrice();
	if(userData.userinfo.id!=null){
		merchant.buyerUserId=userData.userinfo.id;
		console.log("当前用户id",merchant.buyerUserId);
	}
});


//获取支付价格
const GetPrice=()=>{
	let paraData={};
	uni.$tools.Reqeust('/api/getPrice',paraData,'POST').then((res:any)=>{
		console.log("获取获取支付价格",res);
		if(res.data.code===200){
			if(res.data.definedprice!=null){
				realPayMoney.value=res.data.definedprice.setmoney;
				merchant.price=res.data.definedprice.setmoney;
				console.log("支付金额",realPayMoney.value);
			}
		}else{
			uni.$tools.Toast(res.data.msg);
		}
	});
}

//生成订单
const GenerateOrder=async ()=>{
	
	if(payMode.value===ai_buyName.value){  //ai_buyName.value='Ai慢病管理'	
		//uni.$tools.Toast("请选择购买月份");
		if(aiPay.value===false) return;
	}
	
	// if(!/\S/.test(merchant.name)){
	// 	uni.$tools.Toast("给店铺起个名称")
	// 	return;
	// }
	// if(!uni.$u.test.chinese(merchant.name)){
	// 	uni.$tools.Toast("商家名称请输入全中文")
	// 	return;
	// }
	// if(!/\S/.test(merchant.tel)){
	// 	uni.$tools.Toast("填写联系方式")
	// 	return;
	// }
	// if(!uni.$u.test.mobile(merchant.tel)){
	// 	uni.$tools.Toast("手机号码格式不正确")
	// 	return;
	// }
	// if(merchant.adr==='请选择' || !/\S/.test(merchant.adr)){
	// 	uni.$tools.Toast("请选择商家地址")
	// 	return;
	// }
	// if(merchant.class==='请选择' || !/\S/.test(merchant.class)){
	// 	uni.$tools.Toast("请选择所属分类")
	// 	return;
	// }
	// if(merchant.desc==='' || !/\S/.test(merchant.desc)){
	// 	uni.$tools.Toast("请填写商家介绍")
	// 	return;
	// }
	// if(merchant.photo==='' || !/\S/.test(merchant.photo)){
	// 	uni.$tools.Toast("请上传一张商家店铺或店招环境图片")
	// 	return;
	// }
	// if(merchant.month==='' || !/\S/.test(merchant.month)){
	// 	uni.$tools.Toast("请选择入驻时长")
	// 	return;
	// }
	// if(merchant.price<=0){
	// 	uni.$tools.Toast("请选择入驻时长")
	// 	return;
	// }
	if(merchant.buyerUserId===null || merchant.buyerUserId===''){
		uni.$tools.Toast("当前购买者id已失效")
		setTimeout(()=>{
			uni.$tools.GoUrl("/pages/login/login",0); //跳转到登录
		},1000);
		return;
	}
	
	uni.showLoading({
		title:"正在支付"
	})
	setTimeout(()=>{
		uni.hideLoading();
	},3000);
	/*生成订单*/
	let paraData={
		userid:merchant.buyerUserId,
		ordername:merchant.name,
		adrphone:merchant.tel,
		adradress:merchant.adr,
		productname:merchant.class, //productname 购买套餐分类
		adrdetail:merchant.desc, //商家简介
		totalpay:realPayMoney.value, //实际支付金额
		productimg:merchant.photo, //商家图片
		buynumber:merchant.month.replace("个月",""), //入驻时长
		//beizhu:merchant.lat+","+merchant.lng, //经纬度 lat,lng 逗号分隔 (20.12345,110.666588)，后台分解
		beizhu:'',
		orderprice:merchant.price //支付金额
	}
	
	//追加参数
	if(payMode.value===ai_buyName.value){  //ai_buyName.value='Ai慢病管理'
		paraData.mbuserid=mbuserid.value;
		let nowDate=Date_C();
		paraData.starttime=nowDate; //购买生效日期
		paraData.endtime=addMonths(nowDate,parseInt(paraData.buynumber));
	}
	console.log("下单参数:",paraData);
	
	paraTest.value=JSON.stringify(paraData);
	
	generateOrder("/api/generateOrder",paraData).then(res=>{
		console.log("服务器返回",res);
		if(res.data.code===200){
			let orderNo=res.data.orderInfo.orderno;
			let payMoney=merchant.price;
			let productName=merchant.class;
			//生成订单后，上传商家订单号+图片店招 更新
			//uploadMerchantImage(orderNo);
			//调用支付订单
			payOrder("/api/orderPay",orderNo,productName,realPayMoney.value);
		}		
	});
	//*/
}


</script>

<style>
	page{
		background:#f6eade;
	}
</style>
<style lang='scss' scoped>
	@import "buy.scss";
</style>